package com.example.children.controller;

import com.example.children.Exception.RegisterException;
//import com.example.children.Service.RegisterService;
import com.example.children.Service.RegisterService;
import com.example.children.Util.MD5Util;
import com.example.children.Util.Tools;
import com.example.children.Util.UUIDGenerator;
import com.example.children.Util.tool;
import com.example.children.Model.User;
import com.example.children.Model.ResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;


@RestController
//@CrossOrigin(origins = {"http://localhost:8080","http://localhost:63342"}) // 允许该源
//@CrossOrigin(origins = "http://localhost:63342") // 允许该源
@RequestMapping("/Register")  //类名
public class Register {

    @Autowired
    private RegisterService registerService;


    @PostMapping("/register") //方法名
    public ResponseModel<Map<String, String>> register_2(@RequestBody User user) throws NoSuchAlgorithmException {
        System.out.println("进入register方法：");
        Integer code= Tools.Success;
        String msg= tool.success;
        Map<String, String> toKenMap =new HashMap();
        if((user.getUsername()==null || user.getUsername().equals("")))
            throw new RegisterException("用户名不能为空");
        if(!registerService.isValidPassword(user.getPassword()))
            throw new RegisterException("密码格式错误，请输入至少为 8 个字符，并且含有一个数字，含有以下字符的形式：!@#$%^&*");
//         检查某个用户是否存在
        User exists = registerService.isUsernameExist(user.getPassword());
        String test=registerService.isInvitationCode(user.getInvitationCode());
        boolean is=registerService.isTeacherId(user.getId());
        user.setInvitationCode(test);
        if (exists==null&&test!=null&&is) {
            // 生成UUID
//            String uuid = UUIDGenerator.generateNumericUUID(8);
//            user.setId(uuid);
            user.setRole("teacher");
                    String md5Password = MD5Util.encrypt(user.getPassword());
        user.setPassword(md5Password);
            registerService.insertUser(user);
            System.out.println("Yes");
        }
        else{
            System.out.println("No");
            throw new RegisterException("用户名重复！！---错误");
        }
        return new ResponseModel<>(code,msg,toKenMap);//响应给前端的对象
    }





}

